package com.lzw.mall.common.service.impl;

import com.github.pagehelper.PageHelper;
import com.lzw.mall.common.entity.Category;
import com.lzw.mall.common.exception.BusinessException;
import com.lzw.mall.common.mapper.CategoryMapper;
import com.lzw.mall.common.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzw.mall.common.util.Constants;
import com.lzw.mall.common.vo.CategoryVO;
import com.lzw.mall.common.vo.LayuiTableVO;
import com.lzw.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhenwei
 * @since 2023-03-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public LayuiTableVO list(Integer page, Integer limit, String keyword) {
        PageHelper.startPage(page,limit);
        return LayuiTableVO.data(categoryMapper.selectListPage(keyword));
    }

    @Override
    public ResultVO avatar(MultipartFile file) {
        ResultVO vo=new ResultVO();
        String fileName=System.currentTimeMillis() + ".png";
        File f=new File("D:\\test01\\"+fileName);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map=new HashMap();
        map.put("imgPath", Constants.UPLOAD_PATH +fileName);
        vo.setCode(0);
        vo.setData(map);
        return vo;
    }

    @Override
    public ResultVO doSave(Category c) {

        ResultVO vo = new ResultVO();
        if (c.getId()==null) {
            vo.setData(baseMapper.insert(c));
        }else {
            updateById(c);
        }
        return vo;
    }

    @Override
    public void doDelete(Integer id) {
        List<Category> list=baseMapper.selectByParentId(id);
        if(list.size()>0){
            throw new BusinessException("存在子商品，不可以删除");
        }
        baseMapper.deleteById(id);
    }

    @Override
    public List<Category> selectByParentId(Integer parentId) {
        return categoryMapper.selectByParentId(parentId);
    }

    @Override
    public List<CategoryVO> indexList() {
            return baseMapper.indexList();
    }
}
